package com.justgame.project.base.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Enumeration;


@WebFilter(filterName = "sqlFilter", urlPatterns = "/*", asyncSupported = true)
public class SqlFilter implements Filter {

    //效验
    protected static boolean sqlValidate(String str) {
        String s = str.toLowerCase();//统一转为小写
        String badStr =
                "select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|table|" +
                        "char|declare|sitename|xp_cmdshell|like|from|grant|use|group_concat|column_name|" +
                        "information_schema.columns|table_schema|union|where|order|by|" +
                        "'\\*|\\;|\\-|\\--|\\+|\\,|\\//|\\/|\\%|\\#";//过滤掉的sql关键字，特殊字符前面需要加\\进行转义
        //使用正则表达式进行匹配
        return s.matches(badStr);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获得所有请求参数名
        Enumeration<String> names = request.getParameterNames();
        StringBuilder sql = new StringBuilder();
        while (names.hasMoreElements()) {
            //得到参数名
            String name = names.nextElement();
            //得到参数对应值
            String[] values = request.getParameterValues(name);
            for (String value : values) {
                sql.append(value);
            }
        }
        if (sqlValidate(sql.toString())) {
            throw new IOException("您发送请求中的参数中含有不合规字符");
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
